package com.beverages.orders.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beverages.orders.client.CustomerCommoditiesClient;
import com.beverages.orders.client.CustomerIndividualClient;
import com.beverages.orders.entity.intermediate.Commodity;
import com.beverages.orders.entity.intermediate.Individual;
import com.beverages.orders.entity.Orders;
import com.beverages.orders.entity.intermediate.Toppings;
import com.beverages.orders.entity.dto.intermediate.IndividualDTO;
import com.beverages.orders.entity.dto.OrdersDTO;
import com.beverages.orders.service.IOrdersService;
import com.beverages.orders.mapper.OrdersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private CustomerCommoditiesClient customerCommoditiesClient;

    @Autowired
    private CustomerIndividualClient customerIndividualClient;

    @Override
    public OrdersDTO convertOrdersEntityToOrdersDTO(Orders orders){

        OrdersDTO dto = new OrdersDTO();
        BeanUtils.copyProperties(orders, dto);

        if (orders.getCustomerId() != null) {
            IndividualDTO individualDTO = customerIndividualClient.getIndividualDTOById(orders.getCustomerId()).getData();
            if (individualDTO != null) {
                dto.setCustomerName(individualDTO.getNickname());
                dto.setCustomerPhone(individualDTO.getPhone());
            }
        }

        if (orders.getMilkteaId() != null) {
            Commodity commodity = customerCommoditiesClient.getCommodityById(orders.getMilkteaId()).getData();
            if (commodity != null) {
                dto.setMilkteaName(commodity.getMilkteaName());
            }
        }

        String sugarLevelString;
        switch (orders.getSugarLevel()) {
            case 4:
                sugarLevelString = "全糖";
                break;
            case 3:
                sugarLevelString = "四分之三糖";
                break;
            case 2:
                sugarLevelString = "半糖";
                break;
            case 1:
                sugarLevelString = "四分之一糖";
                break;
            case 0:
                sugarLevelString = "无糖";
                break;
            default:
                sugarLevelString = "未知糖度";
                break;
        }
        dto.setSugarLevel(sugarLevelString);

        String iceLevelString;
        switch (orders.getIceLevel()) {
            case 2:
                iceLevelString = "正常冰";
                break;
            case 1:
                iceLevelString = "少冰";
                break;
            case 0:
                iceLevelString = "无冰";
                break;
            default:
                iceLevelString = "未知冰度";
                break;
        }
        dto.setIceLevel(iceLevelString);

        if (orders.getToppings() != null) {
            // 使用逗号作为分隔符分割字符串
            String[] toppingsIdsArray = orders.getToppings().split(",");

            // 创建一个列表来存储小料
            List<Integer> toppingsIdsList = new ArrayList<>();
//            dto.setToppingsIds(toppingsIdsList);

            // 遍历字符串数组，将每个字符串转换为整数并添加到列表中
            for (String topping : toppingsIdsArray) {
                int num = Integer.parseInt(topping);
                toppingsIdsList.add(num);
            }
            dto.setToppingsIds(toppingsIdsList);
            List<Toppings> toppings = customerCommoditiesClient.getToppingsByIds(toppingsIdsList).getData();
            if (toppings != null) {
                List<String > toppingsNameList = new ArrayList<>();
                for (Toppings topping : toppings) {
                    String name = topping.getName();
                    toppingsNameList.add(name);
                }
                dto.setToppings(toppingsNameList);
            }
        }

        if(orders.getOrderTime() != null){
            dto.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getOrderTime()));
        }

        String orderStatusString;
        switch (orders.getOrderStatus()) {
            case 1:
                orderStatusString = "已下单";
                break;
            case 0:
                orderStatusString = "已撤单";
                break;
            default:
                orderStatusString = "未知订单状态";
                break;
        }
        dto.setOrderStatus(orderStatusString);

        if(orders.getCompletionTime() != null){
            dto.setCompletionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCompletionTime()));
        }

        String completionStatusString;
        switch (orders.getCompletionStatus()) {
            case 0:
                completionStatusString = "待制作";
                break;
            case 1:
                completionStatusString = "准备制作";
                break;
            case 2:
                completionStatusString = "制作中";
                break;
            case 3:
                completionStatusString = "制作完成";
                break;
            default:
                completionStatusString = "未知制作状态";
                break;
        }
        dto.setCompletionStatus(completionStatusString);

        String placeStatusString;
        switch (orders.getPlaceStatus()) {
            case 1:
                placeStatusString = "已取";
                break;
            case 0:
                placeStatusString = "未取";
                break;
            default:
                placeStatusString = "未知取物状态";
                break;
        }
        dto.setPlaceStatus(placeStatusString);

        if (orders.getHolderIds() != null) {
            String[] holderIdsArray = orders.getHolderIds().split(",");
            List<Integer> holderIdsList = new ArrayList<>();
            for (String holderId : holderIdsArray) {
                int num = Integer.parseInt(holderId);
                holderIdsList.add(num);
            }
            dto.setHolderIds(holderIdsList);
        }

        return dto;
    }

    /**  Just need :
     * a milkteaId,
     * a customerId,
     * a sugarLevel,
     * an iceLevel,
     * a list of toppingsIds,
     * a count.
     */
    @Override
    public Orders convertOrdersDTOToOrdersEntity(OrdersDTO dto){
        Orders orders = new Orders();
//        BeanUtils.copyProperties(dto, orders);

        orders.setMilkteaId(dto.getMilkteaId());

        orders.setCustomerId(dto.getCustomerId());

        Integer sugarLevel = 0;
        switch (dto.getSugarLevel()) {
            case "全糖":
                sugarLevel = 4;
                break;
            case "四分之三糖":
                sugarLevel = 3;
                break;
            case "半糖":
                sugarLevel = 2;
                break;
            case "四分之一糖":
                sugarLevel = 1;
                break;
            case "无糖":
                sugarLevel = 0;
                break;
        }
        orders.setSugarLevel(sugarLevel);

        Integer iceLevel = 0;
        switch (dto.getIceLevel()) {
            case "正常冰":
                iceLevel = 2;
                break;
            case "少冰":
                iceLevel = 1;
                break;
            case "无冰":
                iceLevel = 0;
                break;
        }
        orders.setIceLevel(iceLevel);

        BigDecimal totalPrice = BigDecimal.valueOf(0);
        List<Integer> toppingsIds = dto.getToppingsIds();
        if (toppingsIds != null && toppingsIds.size() > 0){
            orders.setToppings(String.join(",", toppingsIds.stream().map(String::valueOf).toArray(String[]::new)));
            List<Toppings> toppings = customerCommoditiesClient.getToppingsByIds(toppingsIds).getData();
            BigDecimal toppingsTotalPrice = BigDecimal.valueOf(0);
            if (toppings != null) {
                for (Toppings topping : toppings) {
                    toppingsTotalPrice = toppingsTotalPrice.add(topping.getPrice());
                }
                totalPrice = totalPrice.add(toppingsTotalPrice);
            }
        }else {
            orders.setToppings("0");
        }

        BigDecimal milkteaPrice = BigDecimal.valueOf(0);
        Commodity commodity = customerCommoditiesClient.getCommodityById(dto.getMilkteaId()).getData();
        milkteaPrice = milkteaPrice.add(commodity.getPrice());
        milkteaPrice = milkteaPrice.multiply(BigDecimal.valueOf(dto.getCount()));
        totalPrice = totalPrice.add(milkteaPrice);

        orders.setTotalPrice(totalPrice);


        Date currentDate = new Date();
        orders.setOrderTime(currentDate);
        orders.setOrderStatus(1);

        orders.setCompletionStatus(0);

        orders.setPlaceStatus(0);

        orders.setHolderIds("0");

        // 获取年月日时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String formattedDate = sdf.format(currentDate);

        String orderNumber = "114" + dto.getCustomerId() + dto.getMilkteaId() + dto.getCount() + formattedDate + "514";
        orders.setOrderNumber(orderNumber);

        orders.setCount(dto.getCount());

        return orders;
    }

    //顾客余额扣除、商家余额增加
    @Override
    public void pay(Orders orders){
        //顾客余额扣除
        Individual customer = customerIndividualClient.getIndividualById(orders.getCustomerId()).getData();
        BigDecimal customerInitialBalance = customer.getBalance();
        BigDecimal commoditiesTotalPrice = orders.getTotalPrice();
        customer.setBalance(customerInitialBalance.subtract(commoditiesTotalPrice));
        customerIndividualClient.saveIndividual(customer);
        //商家收款
        Individual merchant = customerIndividualClient.getIndividualById(1).getData();
        BigDecimal merchantInitialBalance = merchant.getBalance();
        merchant.setBalance(merchantInitialBalance.add(commoditiesTotalPrice));
        customerIndividualClient.saveIndividual(merchant);
    }
}
